import React, { Component, useEffect, useState, useRef } from "react";
import {
  Input,
  Space,
  Radio,
  Row,
  Col,
  Table,
  Button,
  Tag,
  Popconfirm,
  message,
  Modal,
  Form,
  Select,
  Card,
  Avatar,
} from "antd";
import moment from "moment";
import LinesEllipsis from "react-lines-ellipsis";
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
  HeartOutlined,
  StarTwoTone,
  StarOutlined,
  LikeTwoTone,
  LikeOutlined,
  HourglassOutlined,
  FireOutlined,
  LikeFilled,
  StarFilled,
  AudioOutlined,
} from "@ant-design/icons";
import { baseURL } from "../../../api/ajax";
import { http } from "../../../api";
import { HashHistory } from "../../../utils";
const { Search } = Input;
const { Option } = Select;
export default function ChooseList() {
  // 属性
  const [codelist, setCodelist] = useState([]);
  const [flag, setFlag] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [chooseDetails, SetChooseDetails] = useState({});
  const [isModalVisible, setIsModalVisible] = useState(true);
  const [isModalVisible1, setIsModalVisible1] = useState(true);
  const [content, setContent] = useState({});
  const [chooselist, setChooselist] = useState([]);
  const [taotilist, setTaotilist] = useState([]);
  const spanhove2 = useRef();
  const spanhove1 = useRef();
  const showanswer = useRef();
  const [shownumber, setShownumber] = useState(0);
  useEffect(() => {
    var list = [];
    http.categorylist().then((res) => {
      if (res.data.code == 200) {
        res.data.val.map((item) => {
          list.push(item.code);
        });
      }
      setCodelist(list);
    });
    http.getchoose({ status: 1 }).then((res) => {
      var choose = res.data.val;
      if (choose) {
        choose.forEach((item, i) => {
          http.getuserinfo({ phone: item.phone }).then((res) => {
            // console.log(res, 1);
            choose[i].avatar = res.data.val[0].avatar;
            choose[i].username = res.data.val[0].username;
          });
        });
      }
      setTimeout(() => {
        setChooselist(choose);
      }, 1000);
    });
    console.log(isModalVisible);
  }, [isModalVisible]);

  //对话框
  const showModal = (item) => {
    SetChooseDetails(item);
    setFlag(true);
    http.userlist().then((res) => {
      if (res.data.code == 200) {
        res.data.val.collectArr.forEach((result, i) => {
          if (result == item._id) {
            setIsModalVisible(false);
            spanhove1.current.style.background = "skyblue";
          }
        });
        res.data.val.starArr.forEach((result, i) => {
          if (result == item._id) {
            setIsModalVisible1(false);
            spanhove2.current.style.background = "skyblue";
          }
        });
      }
    });
  };

  const handleOk = () => {
    setFlag(false);
    showanswer.current.style.display = "none";
  };

  const handleCancel = () => {
    setFlag(false);
    showanswer.current.style.display = "none";
  };

  const suffix = (
    <AudioOutlined
      style={{
        fontSize: 16,
        color: "#1890ff",
      }}
    />
  );

  const handleChange = (value) => {
    if (value == 1) {
      setShownumber(1);
      setChooselist([]);
      http.searchtaotilist().then((res) => {
        // console.log(res);
        setTaotilist(res.data.result);
      });
    } else {
      setShownumber(0);
      setTaotilist([]);
      http.getchoose({ status: 1 }).then((res) => {
        var choose = res.data.val;
        choose.forEach((item, i) => {
          http.getuserinfo({ phone: item.phone }).then((res) => {
            choose[i].avatar = res.data.val[0].avatar;
            choose[i].username = res.data.val[0].username;
          });
        });
        setTimeout(() => {
          setChooselist(choose);
        }, 1000);
      });
    }
  };

  // table方法
  const onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    setSelectedRowKeys({ selectedRowKeys });
  };
  const onSearch = (value) => {
    if (shownumber == 1) {
      http.searchtaotilist({ str: value }).then((res) => {
        var temp = res.data.val.concat(res.data.result);

        setTaotilist(temp);
      });
    } else {
      http.searchchoose({ str: value, status: 1 }).then((res) => {
        var temp = res.data.val.concat(res.data.result);

        setChooselist(temp);
      });
    }
  };
  const changeRadio = (e) => {
    if (shownumber == 1) {
      http.sorttaoti({ code: e.target.value }).then((res) => {
        setTaotilist(res.data.val);
      });
    } else {
      http.sortchoose({ status: 1, code: e.target.value }).then((res) => {
        setChooselist(res.data.val);
      });
    }
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  //表单
  const layout = {
    wrapperCol: {
      span: 16,
    },
  };
  const tailLayout = {
    wrapperCol: {
      span: 16,
    },
  };
  const changeCorrect = (e) => {
    setContent(e.target.value);
  };

  // 自定义
  const choosedetails = (item) => {
    showModal(item);
  };
  const showsubject = () => {
    showanswer.current.style.display = "block";
  };
  const submitchoose = () => {
    console.log(content, chooseDetails.correct);
    if (content == chooseDetails.correct) {
      message.info("选择正确");
    } else {
      message.error("选择错误");
    }
  };

  // 点赞
  const changstar = () => {
    // console.log(chooseDetails);
    if (isModalVisible1) {
      http
        .adddianzan({
          type: 1,
          _id: chooseDetails._id,
          heat: chooseDetails.heat,
          dianzan: chooseDetails.dianzan,
        })
        .then((res) => {
          if (res.data.code == 200) {
            spanhove2.current.style.background = "skyblue";
            message.info("点赞成功");
            setIsModalVisible1(!isModalVisible1);
          }
        });
    } else {
      //   console.log(1);
      http
        .deletedianzan({
          type: 1,
          _id: chooseDetails._id,
          heat: chooseDetails.heat,
          dianzan: chooseDetails.dianzan,
        })
        .then((res) => {
          if (res.data.code == 200) {
            spanhove2.current.style.background = "rgb(0,0,0,10%)";
            message.error("取消成功");
            setIsModalVisible1(!isModalVisible1);
          }
        });
    }
  };
  // 收藏
  const changcollect = () => {
    if (isModalVisible) {
      setIsModalVisible1(false);
      //   console.log(isModalVisible);
      http
        .addshouchang({
          type: 1,
          _id: chooseDetails._id,
          heat: chooseDetails.heat,
          shouchang: chooseDetails.shouchang,
        })
        .then((res) => {
          if (res.data.code == 200) {
            spanhove1.current.style.background = "skyblue";
            message.info("点赞成功");
          }
        });
    } else {
      setIsModalVisible1(true);

      http
        .deleteshouchang({
          type: 1,
          _id: chooseDetails._id,
          heat: chooseDetails.heat,
          shouchang: chooseDetails.shouchang,
        })
        .then((res) => {
          if (res.data.code == 200) {
            spanhove1.current.style.background = "rgb(0,0,0,10%)";
            message.error("取消成功");
          }
        });
    }
  };
  // 表单

  const onFinish = (values) => {
    // console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    // console.log('Failed:', errorInfo);
  };

  // 套题详情
  const taotidetails = (item) => {
    HashHistory.push("/main/tiku/choose/taotidetails:item=" + item._id);
  };

  return (
    <div>
      <div
        style={{
          width: 500,
          height: 50,
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 20,
        }}
      >
        <Search
          placeholder="技术关键字"
          allowClear
          enterButton="搜索"
          size="large"
          onSearch={onSearch}
        />
        <Select
          defaultValue={0}
          style={{ width: 120, marginBottom: 10 }}
          onChange={handleChange}
        >
          <Option value={0}>选择题</Option>
          <Option value={1}>套题</Option>
        </Select>
      </div>
      <Row style={{ height: 30 }}>
        <Col style={{ height: 30 }}>
          <Radio.Group
            onChange={changeRadio}
            defaultValue="a"
            style={{ height: 30 }}
          >
            {codelist &&
              codelist.map((item, i) => {
                return (
                  <Radio.Button
                    value={item}
                    key={i}
                    style={{ marginRight: 10 }}
                  >
                    {item}
                  </Radio.Button>
                );
              })}
          </Radio.Group>
        </Col>
      </Row>

      {chooselist &&
        chooselist.map((item, i) => {
          return (
            <Card
              key={i}
              style={{ width: "60%", padding: " 0 10px", margin: 10 }}
              hoverable
              onClick={() => {
                choosedetails(item);
              }}
            >
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  minHeight: "150px",
                }}
              >
                <div style={{ position: "relative", width: "100%" }}>
                  <div style={{ position: "absolute", top: "30px", left: "0" }}>
                    {item.subject}
                  </div>
                  <div
                    style={{
                      position: "absolute",
                      bottom: "0",
                      left: "0",
                    }}
                  >
                    {item.avatar && (
                      <Avatar
                        src={item.avatar.replace(/public/, baseURL)}
                        size={48}
                      />
                    )}
                    <span style={{ margin: "0 10px", fontSize: "14px" }}>
                      {item.username}
                    </span>
                    <span style={{ fontSize: "12px" }}>
                      {moment(item.time).format("YYYY-MM-DD hh:mm:ss")}
                    </span>
                  </div>
                </div>
                <div style={{ display: "flex", alignItems: "flex-end" }}>
                  <StarFilled
                    style={{
                      marginLeft: 20,
                      marginRight: 5,
                      cursor: "pointer",
                      display: "block",
                    }}
                    className="changeColor"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  />
                  <span>{item.collect}</span>

                  <LikeFilled
                    style={{
                      marginLeft: 20,
                      marginRight: 5,
                      cursor: "pointer",
                      display: "block",
                    }}
                    className="changeColor"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  />
                </div>
              </div>
            </Card>
          );
        })}
      {/* 套题 */}
      {taotilist &&
        taotilist.map((item, i) => {
          return (
            <Card
              key={i}
              style={{ width: "60%", padding: " 0 10px", margin: 10 }}
              hoverable
              onClick={() => {
                taotidetails(item);
              }}
            >
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  minHeight: "150px",
                }}
              >
                <div style={{ position: "relative", width: "100%" }}>
                  <div style={{ position: "absolute", top: "30px", left: "0" }}>
                    <span>卷名:</span>
                    <span>{item.title}</span>
                  </div>
                  <div style={{ position: "absolute", bottom: "0", left: "0" }}>
                    <span>相关技术:</span>
                    <span>{item.technology}</span>
                  </div>
                </div>

                <div style={{ display: "flex", alignItems: "flex-end" }}>
                  <StarFilled
                    style={{
                      marginLeft: 20,
                      marginRight: 5,
                      cursor: "pointer",
                      display: "block",
                    }}
                    className="changeColor"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  />
                  <span>{item.collect}</span>

                  <LikeFilled
                    style={{
                      marginLeft: 20,
                      marginRight: 5,
                      cursor: "pointer",
                      display: "block",
                    }}
                    className="changeColor"
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  />
                </div>
              </div>
            </Card>
          );
        })}

      <Modal
        title="选择题"
        visible={flag}
        key={chooseDetails._id}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {
          <Form
            {...layout}
            name="choose"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            layout="vertical"
          >
            <Form.Item label="题目" name="subject">
              <p>{chooseDetails.subject}</p>
            </Form.Item>

            <Form.Item label="选项" name="answer">
              {chooseDetails.answer && (
                <Radio.Group onChange={changeCorrect} style={{ height: 30 }}>
                  <Radio value="A" style={{ display: "block" }}>
                    A、{chooseDetails.answer[0]}
                  </Radio>
                  <Radio value="B" style={{ display: "block" }}>
                    B、{chooseDetails.answer[1]}
                  </Radio>
                  <Radio value="C" style={{ display: "block" }}>
                    C、{chooseDetails.answer[2]}
                  </Radio>
                  <Radio value="D" style={{ display: "block" }}>
                    D、{chooseDetails.answer[3]}
                  </Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label="题目" name="subject">
              <Button type="primary" onClick={submitchoose}>
                提交答案
              </Button>
            </Form.Item>
            <Form.Item label="题目" name="subject">
              <Button type="primary" onClick={showsubject}>
                显示正确答案答案
              </Button>
              <p style={{ display: "none" }} ref={showanswer}>
                {chooseDetails.correct}
              </p>
            </Form.Item>

            <div style={{ display: "flex", height: 30 }}>
              <p
                style={{
                  marginRight: "10px",
                  width: 50,
                  height: 30,
                  background: "rgb(0,0,0,10%)",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                }}
                className="spanhove1"
                ref={spanhove1}
                onClick={changcollect}
              >
                <StarFilled />
                收藏
              </p>
              <p
                className="spanhove2"
                style={{
                  marginRight: "10px",
                  width: 50,
                  height: 30,
                  background: "rgb(0,0,0,10%)",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                }}
                ref={spanhove2}
                onClick={changstar}
              >
                <LikeFilled />
                点赞
              </p>
            </div>
          </Form>
        }
      </Modal>
    </div>
  );
}

function taoti() {}
